<template>
    <div class="order-customize">
        <!-- 图片上传 -->
        <UserUploader ref="uploader" />

        <!-- 模特预览 -->
        <UxDialog :visible="!!status" @close="status = ''" class="customize-dialog" v-loading="loading">

            <h2 v-text="status == 'edit' ? 'Edit custom layer' : 'Preview'"></h2>

            <!-- 初始化 -->
            <div class="customize-initing" v-if="status == 'initing'">
                <UxLoading />
            </div>

            <!-- 预览 -->
            <div class="customize-preivew" v-else-if="status == 'preview'">
                <ul>
                    <li v-for="model in modelTags" :key="model.id" :style="size">
                        <h4 v-text="$getSurfaceNameFormat(model.surface_name)"></h4>
                        <figure>
                            <DesignerModelPanelRender :model="model" :color="activeColor" :pieces="pieces"
                                                      :size="size" />
                        </figure>
                    </li>
                </ul>

                <div class="customize-preivew-action">
                    <button @click="setStatus('edit')">Edit</button>
                    <button type="primary" @click="saveDesign()">Submit</button>
                </div>

            </div>

            <div class="customize-editor" v-else-if="status == 'edit'">
                <!-- 设计区 -->
                <div class="layout-render" ref="warper">
                    <!-- 效果区 -->
                    <UserBrandingRender :piece="activePiece" ref="render" />
                    <!-- 操作区 -->
                    <DesignerEditorOperate :activeSurface="activeSurface" :activePiece="activePiece"
                                           :activeLayer="activeLayer" @updateLayer="updateLayer($event)"
                                           :lock="layerLock" />
                </div>
                <div class="layout-align">

                    <h3>
                        <img src="https://img.podpartner.com/static/images-20230202/custom-icon.png" alt="" />
                        <strong v-text="activeLayer.name"></strong>
                    </h3>

                    <div class="factor-align">

                        <h4>
                            <figure>
                                <img crossOrigin="anonymous" :style="$fiexImage(activeLayer.w, activeLayer.h, 1)"
                                     v-lazy="getImagePreview(activeLayer)" />
                            </figure>
                            <strong v-text="activeLayer.name"></strong>
                        </h4>

                        <button @click="setAlign('image', 'left')">
                            <svg-icon name="tooler-left" />
                        </button>
                        <button @click="setAlign('image', 'center')">
                            <svg-icon name="tooler-center" />
                        </button>
                        <button @click="setAlign('image', 'right')">
                            <svg-icon name="tooler-right" />
                        </button>
                        <button @click="setAlign('image', 'top')">
                            <svg-icon name="tooler-top" />
                        </button>
                        <button @click="setAlign('image', 'middle')">
                            <svg-icon name="tooler-middle" />
                        </button>
                        <button @click="setAlign('image', 'bottom')">
                            <svg-icon name="tooler-bottom" />
                        </button>
                    </div>

                    <div class="customize-editor-save">
                        <button @click="setStatus('preview', true)">Cancel</button>
                        <button @click="setStatus('preview')" type="primary">Save</button>
                    </div>
                </div>
            </div>
        </UxDialog>

    </div>
</template>
<script>
import DesignResource from "@/utils/DesignResource.js";
import Md5 from "js-md5";
import { mapGetters } from "vuex";
export default {
    name: "OrderCustomize",
    data () {
        return {
            loading: false,
            models: [],
            pieces: [],
            layerLock: [],
            activeColor: {},
            activePiece: null,
            activeLayer: null,
            status: '',
            size: null,
            option: null,
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        activeSurface () {
            const piece = this.activePiece || {};
            return {
                outer_width: piece.outer_width,
                outer_height: piece.outer_height,
                pieces: [piece],
            }
        },
        modelTags () {
            const models = this.models;
            const tag_name = 'flat lay';
            const tag_able = ['hanging', 'flat lay', 'model'].filter(i => models.find(m => (m.model_tag || 'hanging') == i))
            const tag_active = tag_able.indexOf(tag_name) >= 0 ? tag_name : tag_able[0];

            return models.filter(m => (m.model_tag || 'hanging') == tag_active)
        }
    },

    methods: {

        // 更新图层信息
        updateLayer (change) {
            this.activeLayer && Object.keys(change).map(key => {
                this.activeLayer[key] = change[key]
            })
        },

        // 对齐
        setAlign (type, align) {

            const piece = this.activePiece || {};
            const layer = this.activeLayer;

            if (align == 'left') {
                // 水平居左
                layer.x = 0;
            } else if (align == 'center') {
                // 水平居中
                layer.x = 0.5 * (piece.canvas_width - layer.w);
            } else if (align == 'right') {
                // 水平居右
                layer.x = piece.canvas_width - layer.w;
            } else if (align == 'top') {
                // 垂直居上
                layer.y = 0;
            } else if (align == 'middle') {
                // 垂直居中
                layer.y = 0.5 * (piece.canvas_height - layer.h);
            } else if (align == 'bottom') {
                // 垂直居下
                layer.y = piece.canvas_height - layer.h;
            }
        },

        setStatus (status, usedcache) {

            if (status == 'edit') {
                this.cache = { ...this.activeLayer };
            }

            if (usedcache && this.cache) {
                Object.assign(this.activeLayer, this.cache)
                this.cache = null;
            }

            this.status = status;
        },
        getImagePreview (layer) {
            const url = layer.url;
            const cache = DesignResource.getImageByCache(url, { type: "simple", form: "materials" })
            if (cache) {
                return cache.src;
            } else {
                return this.$getLitimgUrl(url, 'medium')
            }

        },

        loadResource () {

            // 预加载所有数据
            const promises = [];
            const option = {
                type: "simple",
                form: "managger",
            };

            // 加载线框图
            this.pieces.map((piece) => {
                if (piece.mask_image) {
                    promises.push(DesignResource.loadImage(piece.mask_image, option));
                }
                piece.layers.map((layer) => {
                    if (layer.type == "image" && layer.url) {
                        promises.push(DesignResource.loadImage(layer.url, { ...option, form: "materials" }));
                    }
                });
            });

            // 加载全部模特图
            this.models.map((item) => {
                item.mask_image && promises.push(DesignResource.loadImage(item.mask_image, option))
            });

            // 背景颜色或纹理
            if (this.activeColor.bg_front) {
                promises.push(DesignResource.loadImage(this.activeColor.bg_front, option));
            }
            if (this.activeColor.bg_back) {
                promises.push(DesignResource.loadImage(this.activeColor.bg_back, option));
            }

            // 加载字体
            promises.push(DesignResource.loadAllFont());

            return Promise.all(promises)
        },

        // 初始化
        startDesign (option) {

            // 获取设计信息
            const getDesignInfo = (callback) => {

                this.setStatus('initing');
                this.$http('Order.getDesignItem', option.designId).then(response => {


                    if (response.code === 0) {

                        const data = response.data || {};
                        const models = data.model_list || [];
                        const pieces = option.pieces;
                        const color = option.color || {};
                        const upload = option.upload;
                        // 选中的
                        const active = {
                            lock: [],
                            layer: null,
                            piece: null,
                        }

                        models.map(item => item.mapping = JSON.parse(item.mapping))


                        // 替换图层，以留白方式填充
                        pieces.map(piece => {
                            piece.layers.map(layer => {
                                const layerId = piece.canvas_name + layer.id;
                                if (layerId != option.layerId) {
                                    // 没有选中
                                    active.lock.push(layerId)
                                } else if (upload) {
                                    // 替换图层，以留白方式填充
                                    const centerX = layer.x + 0.5 * layer.w;
                                    const centerY = layer.y + 0.5 * layer.h;
                                    const scale = Math.min(layer.w / upload.imageW, layer.h / upload.imageH);

                                    layer.imageW = upload.imageW;
                                    layer.imageH = upload.imageH;
                                    layer.name = upload.name;
                                    layer.w = scale * upload.imageW;
                                    layer.h = scale * upload.imageH;
                                    layer.x = centerX - 0.5 * layer.w;
                                    layer.y = centerY - 0.5 * layer.h;
                                    layer.url = upload.url

                                    layer.customize_used = true;
                                    active.piece = piece;
                                    active.layer = layer;
                                } else {
                                    active.piece = piece;
                                    active.layer = layer;
                                }
                            })


                            // 刺绣
                            if (piece.type == 2) {
                                // 要转化为layers，用于渲染
                                piece.layers = piece.platens.map(layer => {
                                    return {
                                        type: 'emb',
                                        platens_id: layer.platens_id || '',
                                        name: layer.name || 0,
                                        w: layer.width || 0,
                                        h: layer.height || 0,
                                        x: layer.left || 0,
                                        y: layer.top || 0,
                                        rotate: layer.rotate || 0,
                                        product_dist: '',
                                        product_preview: layer.product_preview,
                                        product_colors: layer.product_colors,
                                        stitches_count: layer.stitches_count,
                                        price: layer.price || 0,
                                        dists: layer.dists || []
                                    }
                                })
                            }
                        });

                        this.option = option;
                        this.pieces = pieces;
                        this.models = models;
                        this.activeColor = color;
                        this.activePiece = active.piece;
                        this.activeLayer = active.layer;
                        this.layerLock = active.lock;
                        return this.loadResource();

                    } else {
                        return Promise.reject(response.msg)
                    }

                }).then(resource => {
                    this.setStatus('preview');
                    callback && callback()
                }).catch(error => {

                    console.log(error);
                    this.setStatus('');
                    this.$uxMessage.warning('Data request failed');
                    callback && callback()
                })
            }

            if (option.upload) {
                // 上传图片
                const email = (this.userInfo || {}).email;
                const folder = email ? Md5(email) : 'order';
                const path = 'data/pod/file/' + folder;

                // 预加载图片
                this.$refs.uploader && this.$refs.uploader.startUpload({ path: path }, result => {

                    if (result) {
                        option.upload = {
                            image: result.image,
                            imageW: result.image.width,
                            imageH: result.image.height,
                            name: result.name,
                            url: result.url,
                        }

                        DesignResource.setImageCache(result.url, result.image)
                        getDesignInfo(() => this.$refs.uploader.close());
                    } else {
                        this.$uxMessage.warning('Upload failed!');
                    }
                })
            } else {
                getDesignInfo();
            }
        },

        // 保存设计
        saveDesign () {
            // 生成图片
            const request = {
                spu: 'order',
                models: this.models,
                pieces: this.pieces.map((piece, index) => {
                    if (piece.type == 2) {
                        // 刺绣，刺绣没有半自定义
                        return { ...piece, id: piece.id || ('piece-' + index), layers: [] }
                    } else {
                        return { ...piece, id: piece.id || ('piece-' + index) }
                    }
                }),
            };


            this.loading = true;
            this.$http("Drawer.batchDraw", request).then((response) => {
                if (response.code == 0) {
                    const cache = new Map((response.data || []).map((i) => [i.id, i]));
                    const result = {
                        pieces: [],
                        models: [],
                    };

                    // 设计面
                    request.pieces.map((piece, index) => {
                        let select = cache.get(piece.id) || {}
                        let output = (select || {}).output || "";
                        const item = this.pieces[index];

                        // 要把缩略图的litimg去掉
                        select && result.pieces.push({
                            ...item,
                            output_img: output.replace(/-litimg(\.(jpe?g|png))/gi, "$1"),
                            layers: JSON.stringify(item.layers),
                            platens: JSON.stringify(item.platens),
                        });
                    });

                    // 模特
                    request.models.map((item) => {
                        let select = cache.get(item.id) || {}
                        select && result.models.push({
                            id: item.id,
                            model_url: select.output || "",
                            surface_name: item.surface_name,
                            mask_opacity: item.mask_opacity,
                            mask_color: item.mask_color,
                            model_type: item.model_type || 1, // 1旧版，2新版
                            model_tag: item.model_tag || 'hanging',
                            model_name: item.model_name || 'Hanging',
                            model_color: item.model_color || '{}',
                        });
                    });

                    // 格式化保存参数
                    return Promise.resolve(result);


                } else {
                    return Promise.reject(result.msg);
                }
            }).then(drawer => {
                // 保存数据
                const request = {
                    design_info: drawer.pieces,
                    model_img: drawer.models,
                }
                return this.$http('Order.setDesignItem/' + this.option.designId, request).then(response => {
                    if (response.code === 0) {
                        this.option.callback && this.option.callback(drawer)
                        this.setStatus('');
                        this.loading = false;
                        this.$uxMessage.success("Layer updated successfully!");
                    } else {
                        this.loading = false;
                        this.$uxMessage.warning('Failed to save design data, Please try again !');
                    }
                })
            }).catch(error => {
                this.loading = false;
                // this.$uxMessage.warning(error);
            })
        }
    },
    created () {
        this.$on('global:ORDER_DESIGN', this.startDesign)
    },
};
</script>
<style lang="scss" scoped>
.customize-dialog {
    padding: 0 !important;

    &::v-deep {
        .dialog-content {
            width: 100%;
            height: 100%;
            max-width: initial;
            max-height: initial;
            border-radius: 0;

            .dialog-body {
                position: relative;
                overflow: hidden;
                width: 100vw;
                height: 100vh;

                &>h2 {
                    height: 40px;
                    border-bottom: 1px solid #dcdcdc;
                    box-sizing: border-box;
                    line-height: 40px;
                    text-align: center;
                    font-size: 14px;
                }
            }
        }
    }
}

.customize-initing,
.customize-preivew,
.customize-editor {
    position: absolute;
    left: 0;
    top: 40px;
    bottom: 0;
    width: 100%;
}

.customize-preivew {
    display: flex;
    flex-direction: column;
    align-items: center;

    ul {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 50px;
        max-width: calc(200vh - 500px);
        width: 100%;

        h4 {
            text-align: center;
            font-size: 18px;
            line-height: 66px;
            font-weight: normal;
        }

        li {
            width: 50%;
            padding: 0 12px;
            box-sizing: border-box;
        }
    }

    figure {
        position: relative;
        padding-bottom: 100%;
        border-radius: 6px;
        border: 1px solid #dcdcdc;
        overflow: hidden;
    }

    .customize-preivew-action {
        display: flex;
        justify-content: center;
        height: 40px;
        width: 100%;
        min-height: 40px;
        padding: 38px 40px 58px;

        button {
            width: 50%;
            max-width: 240px;
            margin: 0 12px;
        }
    }
}

.customize-editor {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    justify-content: center;
    padding-right: 460px;

    .layout-render {
        flex: 1;
        max-width: calc(100vh - 156px);
        margin: 40px;
        position: relative;
        background: #eee;
        overflow: hidden;

        &::before {
            content: '';
            display: block;
            width: 100%;
            padding-bottom: 100%;
        }

        // 不可删除
        .editor-operate::v-deep .editor-operate-drager button:nth-child(4) {
            display: none;
        }
    }

    .layout-align {
        position: absolute;
        right: 0;
        top: 0;
        width: 460px;
        height: 100%;
        padding-bottom: 106px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        border-left: 1px solid #dcdcdc;

        &>h3 {
            line-height: 96px;
            padding: 0 20px;
            display: flex;
            align-items: center;
            background: #f6f6f6;
            border-bottom: 1px solid #dcdcdc;

            img {
                width: 32px;
                height: 32px;
            }

            strong {
                margin-left: 12px;
                font-size: 22px;
                color: #000000;
                flex: 1;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
        }
    }

    .factor-align {
        margin: 32px 20px;
        padding: 100px 38px 40px;
        border-radius: 6px;
        border: 1px solid #c6c6c6;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        position: relative;

        h4 {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 60px;
            background: #f6f6f6;
            border-bottom: 1px solid #c6c6c6;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            padding: 0 10px;
            border-radius: 6px 6px 0 0;

            figure {
                width: 40px;
                height: 40px;
                background: #ffffff;
                border-radius: 4px;
                border: 1px solid #d8d8d8;
                position: relative;

                img {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    height: 100%;
                }
            }

            strong {
                flex: 1;
                margin-left: 10px;
                font-size: 14px;
                color: #000000;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
        }

        button {
            margin: 5px 0;
            width: 28px;
            height: 28px;
            line-height: 28px;
            text-align: center;
            background: none;
            border: none;
            font-size: 22px;
            color: #666;
            position: relative;

            svg {
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                width: 28px;
                height: 28px;
                stroke: #555;
                fill: #555;
            }

            &:hover {
                svg {
                    stroke: #ea4c89;
                    fill: #ea4c89;
                }
            }
        }
    }

    .customize-editor-save {
        position: absolute;
        left: 0;
        bottom: 0;
        height: 106px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-top: 1px solid #dcdcdc;

        button {
            height: 44px;
            margin: 0 8px;

            &:first-child {
                width: 138px;
            }

            &:last-child {
                width: 202px;
            }
        }
    }
}
</style>
